package com.isa.ssl;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.SecureRandom;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import com.isa.androidwebtrans.R;
import com.isa.app.MyApp;
import com.isa.util.Arguments;

public abstract class HTTPSCoder {
	public static final String PROTOCOL = "TLS";

	private static KeyStore getKeyStore() throws Exception {
		// 实例化密钥库
		KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
		// 加载密钥库
		ks.load(MyApp.getContext().getResources().openRawResource(R.raw.xiaoyu),
				Arguments.PASSWORD.toCharArray());
		return ks;
	}

	// 获取SSLSocketFactory
	private static SSLSocketFactory getSslSocketFactory() throws Exception {
		// 实例化密钥库
		KeyManagerFactory keyManagerFactory = KeyManagerFactory
				.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		// 获得密钥库
		KeyStore keyStore = getKeyStore();
		keyManagerFactory.init(keyStore, Arguments.PASSWORD.toCharArray());
		// 实例化信任库
		TrustManagerFactory trustManagerFactory = TrustManagerFactory
				.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		KeyStore trustStore = getKeyStore();
		trustManagerFactory.init(trustStore);
		// 实例化SSL上下文
		SSLContext ctx = SSLContext.getInstance(PROTOCOL);
		ctx.init(keyManagerFactory.getKeyManagers(),
				trustManagerFactory.getTrustManagers(), new SecureRandom());

		return ctx.getSocketFactory();
	}

	// 为HttpsURLConnection配置SSLSocketFactory
	public static void configSSLSocketFactory(HttpsURLConnection conn)
			throws Exception {
		SSLSocketFactory sslSocketFactory = getSslSocketFactory();
		conn.setSSLSocketFactory(sslSocketFactory);
	}
}
